package src.helloandroid;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View.OnClickListener;

public class HelloAndroid extends Activity
{
    private final static String ALARM_ACTION = "src.helloandroid.intent.action.ALARM_ACTION";
    
    

    class EventHandler extends Handler
    {
        public EventHandler()
        {
            super();
        }

        public EventHandler(Looper looper)
        {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg)
        {
            if (msg.what >= 40 && msg.what <= 50)
            {
                if (50 == msg.what)
                {
                    timer3Button.setEnabled(false);
                }
                if (40 == msg.what)
                {
                    Intent intent = new Intent();
                    intent.setAction(ALARM_ACTION);
                    intent.putExtra("msg", "Time's up!3");
                    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
                    PendingIntent pi;
                    pi = PendingIntent.getBroadcast(HelloAndroid.this, 0, intent, 0);
                    Log.i("test", ""+System.currentTimeMillis());
                    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 8*1000, pi);
                    timer1TV.setText("Times UP!03");
                    timer3Button.setEnabled(true);
                    return;
                }
                timer1TV.setText("Timer3:" + (msg.what - 40));
            }
            if (msg.what >= 0 && msg.what <= 10)
            {
                Log.i("timer1Thread", msg.what + "");
                if (10 == msg.what)
                {
                    timer1Button.setEnabled(false);
                } else if (0 == msg.what)
                {
                    timer1TV.setText("Times UP!01");
                    timer1Button.setEnabled(true);
                    return;
                }
                timer1TV.setText("Timer1:" + msg.what + "");
                timer1ThreadHandler.removeMessages(0);
                timer1ThreadHandler.sendMessage(timer1ThreadHandler
                        .obtainMessage(msg.what - 1 + 1000));
            } else if (msg.what >= 100 && msg.what <= 110)
            {
                if (110 == msg.what)
                {
                    timer2Button.setEnabled(false);
                } else if (100 == msg.what)
                {
                    timer2TV.setText("Times UP!");
                    timer2Button.setEnabled(true);
                    return;
                }
                timer2TV.setText(msg.what - 100 + "");
                timer2ThreadHandler.removeMessages(0);
                timer2ThreadHandler.sendMessage(timer2ThreadHandler
                        .obtainMessage(msg.what - 1 + 1000));
            }
        }
    }

    class TimerThread1 extends Thread
    {
        @SuppressWarnings("unused")
        private Looper mUiThreadLooper, mMyLooper;

        public Looper getLooper()
        {
            return mMyLooper;
        }

        @Override
        public void run()
        {
            Looper.prepare();
            mMyLooper = Looper.myLooper();
            mUiThreadLooper = Looper.getMainLooper();
            timer1ThreadHandler = new Handler(Looper.myLooper())
            {
                @Override
                public void handleMessage(Message msg)
                {
                    try
                    {
                        Thread.sleep(1000);
                        uiThreadHandler.removeMessages(0);
                        uiThreadHandler.sendMessage(uiThreadHandler
                                .obtainMessage(msg.what - 1000));
                    } catch (InterruptedException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            };
            Looper.loop();
        }
    }

    class TimerThread2 extends Thread
    {
        @SuppressWarnings("unused")
        private Looper mUiThreadLooper, mMyLooper;

        public Looper getLooper()
        {
            return mMyLooper;
        }

        @Override
        public void run()
        {
            Looper.prepare();
            mMyLooper = Looper.myLooper();
            mUiThreadLooper = Looper.getMainLooper();
            timer2ThreadHandler = new Handler(Looper.myLooper())
            {
                @Override
                public void handleMessage(Message msg)
                {
                    try
                    {
                        Thread.sleep(1000);
                        uiThreadHandler.removeMessages(0);
                        uiThreadHandler.sendMessage(uiThreadHandler
                                .obtainMessage(msg.what - 1000));
                    } catch (InterruptedException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            };
            Looper.loop();
        }
    }

    class timerThread3 extends AsyncTask<Integer, Integer, Integer>
    {

        @Override
        protected Integer doInBackground(Integer... params)
        {
            // TODO Auto-generated method stub
            for (int mCounter = params[0] + 40; mCounter > 39; mCounter--)
            {
                try
                {
                    Thread.sleep(1000);
                } catch (InterruptedException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Log.i("Async", mCounter + "");
                publishProgress(mCounter);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress)
        {
            uiThreadHandler.sendMessage(uiThreadHandler
                    .obtainMessage(progress[0]));
        }
    }

    /** Called when the activity is first created. */
    // views
    private Button timer1Button;// the 1st timer button
    private Button timer2Button;// the 2nd timer button
    private Button timer3Button;// the 3rd timer button
    private TextView infoTV;// the infomation textview
    private TextView timer1TV;// the 1st timer textview
    private TextView timer2TV;// the 2nd timer textview
    // the 1st to the 5th items of option menu
    private static final int OPTION_MENU_ITEM_1 = Menu.FIRST;
    private static final int OPTION_MENU_ITEM_2 = Menu.FIRST + 1;
    private static final int OPTION_MENU_ITEM_3 = Menu.FIRST + 2;
    private static final int OPTION_MENU_ITEM_4 = Menu.FIRST + 3;
    private static final int OPTION_MENU_ITEM_5 = Menu.FIRST + 4;
    // the 1st to the 4th items of context menu
    private static final int CONTEXT_MENU_ITEM_1 = Menu.FIRST + 6;
    private static final int CONTEXT_MENU_ITEM_2 = Menu.FIRST + 7;
    private static final int CONTEXT_MENU_ITEM_3 = Menu.FIRST + 8;
    private static final int CONTEXT_MENU_ITEM_4 = Menu.FIRST + 9;
    // 2 item of submenu of
    private static final int SUB_MENU_ITEM_1 = Menu.FIRST + 10;
    private static final int SUB_MENU_ITEM_2 = Menu.FIRST + 11;
    // 2 timer thread
    private TimerThread1 timerThread1;
    private TimerThread2 timerThread2;

    // handler
    private EventHandler uiThreadHandler;// handler of ui handler

    private Handler timer1ThreadHandler = null;// handler of the 1st timer

    // thread
    private Handler timer2ThreadHandler = null;// handler of the 2nd timer
                                               // thread

    @Override
    public boolean onContextItemSelected(MenuItem item)
    {
        final AlertDialog.Builder mAlertDialogBuilder = new AlertDialog.Builder(
                this);
        String[] items = { "cyan", "green", "yellow" };
        switch (item.getItemId())
        {
        case CONTEXT_MENU_ITEM_1:
            mAlertDialogBuilder.setMessage("The text color is changed to RED");
            mAlertDialogBuilder.setPositiveButton("OK",
                    new DialogInterface.OnClickListener()
                    {

                        public void onClick(DialogInterface dialog, int which)
                        {
                            // TODO Auto-generated method stub
                            // do nothing
                        }
                    });
            AlertDialog mWithOkAlertDialog = mAlertDialogBuilder.create();
            mWithOkAlertDialog.show();
            infoTV.setTextColor(Color.RED);
            break;
        case CONTEXT_MENU_ITEM_2:
            mAlertDialogBuilder.setMessage("Change the text color to BLUE?");
            mAlertDialogBuilder.setPositiveButton("YES",
                    new DialogInterface.OnClickListener()
                    {

                        public void onClick(DialogInterface dialog, int which)
                        {
                            // TODO Auto-generated method stub
                            infoTV.setTextColor(Color.BLUE);
                        }
                    });
            mAlertDialogBuilder.setNegativeButton("NO",
                    new DialogInterface.OnClickListener()
                    {

                        public void onClick(DialogInterface dialog, int which)
                        {
                            // TODO Auto-generated method stub
                            // do nothing
                        }
                    });
            AlertDialog mWithChoiceAlertDialog = mAlertDialogBuilder.create();
            mWithChoiceAlertDialog.show();
            break;
        case CONTEXT_MENU_ITEM_3:
            infoTV.setTextColor(Color.WHITE);
            break;
        case CONTEXT_MENU_ITEM_4:
            mAlertDialogBuilder.setTitle("Choose color");
            mAlertDialogBuilder.setItems(items,
                    new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int which)
                        {
                            // TODO Auto-generated method stub
                            switch (which)
                            {
                            case 0:
                                infoTV.setTextColor(Color.CYAN);
                                break;
                            case 1:
                                infoTV.setTextColor(Color.GREEN);
                                break;
                            case 2:
                                infoTV.setTextColor(Color.YELLOW);
                                break;
                            }
                        }
                    });
            /*
             * aDBuilder.setSingleChoiceItems(items, -1, new
             * DialogInterface.OnClickListener() {
             * 
             * public void onClick(DialogInterface dialog, int which) { // TODO
             * Auto-generated method stub switch (which) { case 0:
             * eText1.setTextColor(Color.CYAN); break; case 1:
             * eText1.setTextColor(Color.GREEN); break; case 2:
             * eText1.setTextColor(Color.YELLOW); break; } } });
             */
            AlertDialog mWithMutiChoiceAlertDialog = mAlertDialogBuilder
                    .create();
            mWithMutiChoiceAlertDialog.show();
            break;
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        timer1TV = (TextView) findViewById(R.id.timer1Text);
        timer1TV.setTextSize(20);
        timer2TV = ((TextView) findViewById(R.id.timer2Text));
        timer2TV.setTextSize(20);
        timer1Button = (Button) findViewById(R.id.pressButton);
        timer2Button = (Button) findViewById(R.id.btn2);
        timer3Button = (Button) findViewById(R.id.btn3);
        infoTV = (TextView) findViewById(R.id.showTextedit);
        registerForContextMenu(infoTV);
        uiThreadHandler = new EventHandler();
        timerThread1 = new TimerThread1();
        timerThread1.start();
        timerThread2 = new TimerThread2();
        timerThread2.start();
        timer1Button.setOnClickListener(new OnClickListener()
        {

            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                timer1ThreadHandler.removeMessages(0);
                timer1ThreadHandler.sendMessage(timer1ThreadHandler
                        .obtainMessage(1010));
            }
        });
        timer2Button.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                timer2ThreadHandler.removeMessages(0);
                timer2ThreadHandler.sendMessage(timer2ThreadHandler
                        .obtainMessage(1110));
            }
        });
        timer3Button.setOnClickListener(new OnClickListener()
        {

            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                new timerThread3().execute(10);
            }
        });
        
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo)
    {
        menu.setHeaderTitle("Set Text");
        menu.add(0, CONTEXT_MENU_ITEM_1, 0, "red");
        menu.add(0, CONTEXT_MENU_ITEM_2, 0, "blue");
        menu.add(0, CONTEXT_MENU_ITEM_3, 0, "white");
        menu.add(0, CONTEXT_MENU_ITEM_4, 0, "other color");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, OPTION_MENU_ITEM_1, 0, "1st");
        menu.add(0, OPTION_MENU_ITEM_2, 0, "2nd");
        menu.add(0, OPTION_MENU_ITEM_3, 0, "3rd");
        menu.add(0, OPTION_MENU_ITEM_4, 0, "4th");
        menu.add(0, OPTION_MENU_ITEM_5, 0, "5th");

        SubMenu textSizeSubMenu = menu.addSubMenu("set text size");
        textSizeSubMenu.add(0, SUB_MENU_ITEM_1, 0, "12");
        textSizeSubMenu.add(0, SUB_MENU_ITEM_2, 0, "20");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        String mInfoTextString = "The ";
        switch (item.getItemId())
        {
        case OPTION_MENU_ITEM_1:
            mInfoTextString += "1st";
            break;
        case OPTION_MENU_ITEM_2:
            mInfoTextString += "2nd";
            break;
        case OPTION_MENU_ITEM_3:
            mInfoTextString += "3rd";
            break;
        case OPTION_MENU_ITEM_4:
            mInfoTextString += "4th";
            break;
        case OPTION_MENU_ITEM_5:
            mInfoTextString += "5th";
            break;
        case SUB_MENU_ITEM_1:
            infoTV.setTextSize(12);
            Toast mTextSizeChangedToast1 = Toast.makeText(
                    getApplicationContext(), "text size is changed to 12",
                    Toast.LENGTH_SHORT);
            mTextSizeChangedToast1.show();
            return true;
        case SUB_MENU_ITEM_2:
            infoTV.setTextSize(20);
            Toast mTextSizeChangedToast2 = Toast.makeText(
                    getApplicationContext(), "text size is changed to 20",
                    Toast.LENGTH_SHORT);
            mTextSizeChangedToast2.show();
            return true;
        }
        mInfoTextString += " menu item is pressed!";
        // eText1 = (TextView) findViewById(R.id.showTextedit);
        infoTV.setText(mInfoTextString);
        return true;
    }
}
